<?php
namespace App\Http\Controllers\Api\FlyGo;

use App\Models\Activity\AlipayCustomerCardMap;
use App\Models\Card\CardCoupon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Faker\Provider\Uuid;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Models\Goods\GoodsSale;
use App\Models\Customer\Customer;
use App\Models\Bill\Bill;
use App\Models\Bill\BillGoods;
use App\Models\Bill\BillPay;
use App\Models\Bill\BillUseCardCoupon;
use Mockery\Exception;

class BillController extends Controller
{

    private $datetime; //日期

    private $totalMoney = 0; //商品总金额

    private $totalPaid = 0; //商品实售总金额

    private $totalPoints = 0; //商品总赠送积分

    private $pointsPrice = 0; //商品总积分价格

    private $pointsMoney = 0; //积分抵扣金额

    private $balanceMoney = 0; //余额抵扣金额

    private $cardMoney = 0; //代金卡抵扣金额

    private $subtractMoney = 0; //订单立减金额

    private $couponMoney = 0; //优惠券抵扣金额

    private $totalAmount = 0; //商品总数量

    private $payable = 0; //订单应付款金额

    private $billPayData = []; //存放订单支付方式的数组

    private $billGoodsData = []; //存放商品的数组

    private $bill_no; //订单号

    private $operator; //操作人

    private $usePromotion = []; //存放使用促销

    /**
     * 订单数据格式化
     * @param Request $request
     */
    public function orderFormat( Request $request )
    {

        $userId = $request->input('userId');
        if (empty($userId)) {
            return response()->json(['code' => 10001, 'message' => '缺少userId参数']);
        }

        $mallID = $request->input('mallID');
        if (empty($mallID)) {
            $mallID = 0;
        }

        //购物车key
        $cart_name = 'shop_cart';

        $auto_code = $cart_name . '_' . $userId;

        $bill_data = self::getCartInfo($auto_code);

        //主信息
        if (empty($bill_data['master'])) {
            return response()->json(['code' => 10002, 'message' => '订单数据错误']);
        }

        //支付方式
        if (!isset($bill_data['master']['payTypeID']) || empty($bill_data['master']['payTypeID'])) {
            return response()->json(['code' => 10003, 'message' => '请选择支付方式']);
        }

        //检查会员信息
        $customer = Customer::find($userId);
        if (!$customer) {
            return response()->json(['code' => 10004, 'message' => '会员信息没有找到']);
        }

        $this->operator = $customer->custID;

        $this->datetime = date('Y-m-d H:i:s', time());

        try {

            //订单号
            $this->bill_no = generate_seqno('seqno_bill', '1', true);

            //保存订单商品信息（普通商品）
            if (isset($bill_data['goods']['general']) && !empty($bill_data['goods']['general'])) {

                foreach ($bill_data['goods']['general'] as $general) {

                    if (isset($general['is_buy']) && $general['is_buy'] == 0) {
                        continue;
                    }

                    if (!ebsig_is_int($general['goods_amount'])) {
                        continue;
                    }

                    //统计订单商品数据
                    $this->totalBillGoodsData($general);

                    $this->createBillGoodsData($general, 1);
                }
            }

            //购物袋
            if (isset($bill_data['goods']['shopping_bag']) && !empty($bill_data['goods']['shopping_bag'])) {

                foreach ($bill_data['goods']['shopping_bag'] as $bag) {

                    if (!ebsig_is_int($bag['goods_amount'])) {
                        continue;
                    }

                    //统计订单商品数据
                    $this->totalBillGoodsData($bag, 0);

                    $this->createBillGoodsData($bag, 2);
                }
            }

            if ($this->totalAmount == 0) {
                throw new Exception('购物车未添加商品', 404);
            }

            //优惠券具体优惠方式：cardType:1、代金券 2、折扣券
            if (isset($bill_data['use_coupon'])) {

                if ($bill_data['use_coupon']['cardType'] == 1) {
                    $this->couponMoney += $bill_data['use_coupon']['amount'];
                }

                if ($bill_data['use_coupon']['cardType'] == 2 && !empty($bill_data['use_coupon']['discount'])) {
                    $this->couponMoney += $bill_data['use_coupon']['amount'];
                }
            }

            //计算订单应付金额
            $this->calculationBillPayable(0);

            //保存订单支付信息
            if ($this->payable >= 0 ) {
                $this->createBillPayData($bill_data['master']['payTypeID'], $bill_data['master']['payTypeName'], $bill_data['master']['pay_type'], $this->payable);
            }

            //保存订单主表信息
            $bill_data['master']['uuid'] = str_replace('-', '', Uuid::uuid());
            $bill_data['master']['timeStamp'] = $this->datetime;
            $bill_data['master']['creator'] = $this->operator;
            $bill_data['master']['createTime'] = $this->datetime;
            $bill_data['master']['bill_no'] = $this->bill_no;
            $bill_data['master']['pcustID'] = $userId;
            $bill_data['master']['custID'] = $this->operator;
            if ($this->payable == 0) {
                $bill_data['master']['pay_status'] = 1;
            } else {
                $bill_data['master']['pay_status'] = 0;
            }
            $bill_data['master']['bill_status'] = 0;
            $bill_data['master']['bill_totalMoney'] = $this->totalMoney;
            $bill_data['master']['bill_totalPaid'] = $this->totalPaid;
            $bill_data['master']['bill_totalPoints'] = $this->totalPoints;
            $bill_data['master']['bill_subtract_money'] = $this->subtractMoney;
            $bill_data['master']['bill_points_money'] = $this->pointsMoney;
            $bill_data['master']['bill_balance_money'] = $this->balanceMoney;
            $bill_data['master']['bill_coupon_money'] = $this->couponMoney;
            $bill_data['master']['bill_card_money'] = $this->cardMoney;
            $bill_data['master']['bill_total_amount'] = $this->totalAmount;
            $bill_data['master']['bill_tariff_money'] = 0;
            $bill_data['master']['added_value_tax'] = 0;
            $bill_data['master']['consumption_tax'] = 0;
            $bill_data['master']['bill_cross_border'] = 0;
            $bill_data['master']['bill_payable'] = $this->payable;
            $bill_data['master']['billPlatform'] = 1;
            $bill_data['master']['billChannel'] = 3;
            $bill_data['master']['mallID'] = $mallID;

            $bill_data['goods'] = $this->billGoodsData['list'];
            if ($this->billGoodsData['name']) {
                $bill_data['master']['goods_name_str'] = implode(',', $this->billGoodsData['name']);
            }
            $bill_data['pay'] = $this->billPayData['list'];
            if ($this->billPayData['id']) {
                $bill_data['master']['pay_id_str'] = implode(',', $this->billPayData['id']);
            }
            if ($this->billPayData['name']) {
                $bill_data['master']['pay_name_str'] = implode(',', $this->billPayData['name']);
            }

            //保存会员购买记录
            $bill_data['cust_buy_log'] = [
                'uuid' => str_replace('-', '', Uuid::uuid()),
                'timeStamp' => $this->datetime,
                'creator' => $this->operator,
                'createTime' => $this->datetime,
                'pcustID' => $userId,
                'deliverID' => 0,
                'sendTypeID' => 0,
                'send_region_id' => 0,
                'payTypeID' => $bill_data['master']['payTypeID'],
                'pay_type' => $bill_data['master']['pay_type'],
                'invoiceID' => 0,
                'payment_method_id' => 0,
                'extend_1' => null,
                'extend_2' => null,
                'extend_3' => null,
                'extend_4' => null,
                'extend_5' => null,
                'extend_6' => null
            ];

            //订单日志
            $bill_data['log'] = [
                'uuid' => str_replace('-', '', Uuid::uuid()),
                'timeStamp' => $this->datetime,
                'creator' => $this->operator,
                'createTime' => $this->datetime,
                'logCategoryID' => 1,
                'logItem' => $this->bill_no,
                'extend_1' => null,
                'extend_2' => null,
                'extend_5' => 0
            ];

            //优惠券
            if (isset($bill_data['use_coupon']) && !empty($bill_data['use_coupon'])) {
                $bill_data['use_coupon']['uuid'] = str_replace('-', '', Uuid::uuid());
                $bill_data['use_coupon']['creator'] = $this->operator;
                $bill_data['use_coupon']['createTime'] = $this->datetime;
                $bill_data['use_coupon']['timeStamp'] = $this->datetime;
            }

            $bill_data['bill_no'] = $this->bill_no;
            $bill_data['pcustID'] = $userId;
            $bill_data['custID'] = $this->operator;
            $bill_index = $bill_data['bill_no'] . $bill_data['pcustID'];

            //保存订单信息到redis
            Redis::setex('bill_' . $bill_index, 360000, json_encode($bill_data));

            //异步推送订单保存
            $push_array = self::save(['bill_index' => $bill_index]);

            if ($push_array['code'] != 200) {
                return response()->json(['code' => $push_array['code'], 'message' => $push_array['message']]);
            }

            //删除购物车数据
            Redis::del($auto_code);

            return response()->json(['code' => 200, 'message' => 'ok', 'data' => [
                'bill_no'=>$bill_data['bill_no']
            ]]);

        } catch (Exception $e) {
            if ($e->getCode() > 0) {
                return response()->json(['code' => $e->getCode(), 'message' => $e->getMessage()]);
            } else {
                return response()->json(['code' => 500, 'message' => '系统错误']);
            }
        }
    }

    /**
     * 保存订单数据
     * @param $request
     */
    public static function save($request)
    {
        if (!isset($request['bill_index']) || empty($request['bill_index'])) {
            return [ 'code' => 10001, 'message' => '参数错误'];
        }

        $bill_array = Redis::get('bill_' . $request['bill_index']);

        if (!$bill_array) {
            return [ 'code' => 10002, 'message' => '订单数据没有找到'];
        }
        $bill_array = json_decode($bill_array, true);

        //订单号
        $bill_no = $bill_array['bill_no'];

        //订单主表数组
        $master_data = $bill_array['master'];

        //订单商品数组
        $goods_data = $bill_array['goods'];

        //订单支付数组
        $pay_data = $bill_array['pay'];

        //查询会员信息
        $cust_data = Customer::find($bill_array['pcustID']);

        if (!$cust_data) {
            return [ 'code' => 10003, 'message' => '会员信息没有找到'];
        }

        //使用的优惠券数组
        $use_coupon = [];
        if (isset($bill_array['use_coupon']) && !empty($bill_array['use_coupon'])) {
            $use_coupon = $bill_array['use_coupon'];
        }

        /**
         * ======================
         * 订单主信息
         * ======================
         */
        $bill_master_obj = new Bill();
        $bill_master_obj->uuid = $master_data['uuid'];
        $bill_master_obj->timeStamp = $master_data['timeStamp'];
        $bill_master_obj->creator = $master_data['creator'];
        $bill_master_obj->createTime = $master_data['createTime'];
        $bill_master_obj->bill_no = $bill_no;
        $bill_master_obj->pcustID = $master_data['pcustID'];
        $bill_master_obj->custID = $master_data['custID'];
        $bill_master_obj->bill_status = $master_data['bill_status'];
        $bill_master_obj->billPlatform = $master_data['billPlatform'];
        $bill_master_obj->billChannel = $master_data['billChannel'];
        $bill_master_obj->billType = $master_data['billType'];
        $bill_master_obj->pay_status = $master_data['pay_status'];
        $bill_master_obj->bill_totalMoney = $master_data['bill_totalMoney'];
        $bill_master_obj->bill_totalPaid = $master_data['bill_totalPaid'];
        $bill_master_obj->bill_totalPoints = $master_data['bill_totalPoints'];
        $bill_master_obj->bill_pointsPrice = $master_data['bill_pointsPrice'];
        $bill_master_obj->bill_subtract_money = $master_data['bill_subtract_money'];
        $bill_master_obj->bill_points_money = $master_data['bill_points_money'];
        $bill_master_obj->bill_balance_money = $master_data['bill_balance_money'];
        $bill_master_obj->bill_coupon_money = $master_data['bill_coupon_money'];
        $bill_master_obj->bill_card_money = $master_data['bill_card_money'];
        $bill_master_obj->remark = '';
        $bill_master_obj->goods_name_str = $master_data['goods_name_str'];
        $bill_master_obj->bill_total_amount = $master_data['bill_total_amount'];
        $bill_master_obj->bill_tariff_money = $master_data['bill_tariff_money'];
        $bill_master_obj->bill_cross_border = $master_data['bill_cross_border'];
        $bill_master_obj->added_value_tax = $master_data['added_value_tax'];
        $bill_master_obj->consumption_tax = $master_data['consumption_tax'];
        $bill_master_obj->bill_payable = $master_data['bill_payable'];
        if ($master_data['bill_payable'] == 0){  //说明订单已经无需支付（优惠券、积分、余额等抵扣）
            $bill_master_obj->payed_time = date(G_DEFAULT_DATETIME_FORMAT);
        }
        $bill_master_obj->deliverid = isset($master_data['deliverid']) ? $master_data['deliverid'] : 0;
        $bill_master_obj->deliver_name = isset($master_data['deliver_name']) ? $master_data['deliver_name'] : '';
        $bill_master_obj->deliver_province = isset($master_data['deliver_province']) ? $master_data['deliver_province'] : 0;
        $bill_master_obj->deliver_provinceid = isset($master_data['deliver_provinceid']) ? $master_data['deliver_provinceid'] : 0;
        $bill_master_obj->deliver_city = isset($master_data['deliver_city']) ? $master_data['deliver_city'] : 0;
        $bill_master_obj->deliver_cityid = isset($master_data['deliver_cityid']) ? $master_data['deliver_cityid'] : 0;
        $bill_master_obj->deliver_county = isset($master_data['deliver_county']) ? $master_data['deliver_county'] : 0;
        $bill_master_obj->deliver_countyid = isset($master_data['deliver_countyid']) ? $master_data['deliver_countyid'] : 0;
        $bill_master_obj->deliver_address = isset($master_data['deliver_address']) ? $master_data['deliver_address'] : 0;
        $bill_master_obj->deliver_mobile = isset($master_data['deliver_mobile']) ? $master_data['deliver_mobile'] : 0;
        $bill_master_obj->deliver_phone = isset($master_data['deliver_phone']) ? $master_data['deliver_phone'] : 0;
        $bill_master_obj->deliver_fee = isset($master_data['deliver_fee']) ? $master_data['deliver_fee'] : 0;
        $bill_master_obj->deliver_feePaid = isset($master_data['deliver_fee']) ? $master_data['deliver_fee'] : 0;
        $bill_master_obj->mallID = isset($master_data['mallID']) ? $master_data['mallID'] : 0;
        $bill_master_obj->mallCode = isset($master_data['mallCode']) ? $master_data['mallCode'] : 0;
        $bill_master_obj->mallName = isset($master_data['mallName']) ? $master_data['mallName'] : 0;
        $bill_master_obj->zt_id = isset($master_data['zt_id']) ? $master_data['zt_id'] : 0;
        $bill_master_obj->zt_name = isset($master_data['zt_name']) ? $master_data['zt_name'] : 0;
        $bill_master_obj->zt_code = isset($master_data['zt_code']) ? $master_data['zt_code'] : 0;
        $bill_master_obj->activity_id = 0;
        $bill_master_obj->sendTypeID = isset($master_data['sendTypeID']) ? $master_data['sendTypeID'] : 0;
        $bill_master_obj->sendTypeName = isset($master_data['sendTypeName']) ? $master_data['sendTypeName'] : 0;
        $bill_master_obj->ziti = 0;
        $bill_master_obj->send_region_id = 0;
        $bill_master_obj->send_region_name = '';
        $bill_master_obj->pay_type = $master_data['pay_type'];
        $bill_master_obj->payTypeID = $master_data['payTypeID'];
        $bill_master_obj->payTypeName = $master_data['payTypeName'];
        $bill_master_obj->pay_id_str = $master_data['pay_id_str'];
        $bill_master_obj->pay_name_str = $master_data['pay_name_str'];
        $bill_master_obj->pickup_start_time = isset($master_data['pickup_start_time']) ? $master_data['pickup_start_time'] : 0;
        $bill_master_obj->pickup_end_time = isset($master_data['pickup_end_time']) ? $master_data['pickup_end_time'] : 0;
        $bill_master_obj->send_time = isset($master_data['send_time']) ? $master_data['send_time'] : 0;
        $bill_master_obj->invoice = 0;
        $bill_master_obj->supplier_id = 1;
        $bill_master_obj->bill_stock_type = 1;

        /**
         * ======================
         * 订单商品
         * ======================
         */
        $bill_goods_data = [];
        foreach($goods_data as $goods) {

            $bill_goods_data[] = [
                'uuid' => $goods['uuid'],
                'timeStamp' => $goods['timeStamp'],
                'creator' => $goods['creator'],
                'createTime' => $goods['createTime'],
                'bill_no' => $goods['bill_no'],
                'bill_goods_no' => $goods['bill_goods_no'],
                'goods_goodsID' => $goods['goods_goodsID'],
                'goods_postID' => $goods['goods_postID'],
                'product_code' => $goods['product_code'],
                'goods_name' => $goods['goods_name'],
                'goods_spec' => $goods['goods_spec'],
                'goods_amount' => $goods['goods_amount'],
                'goods_storePrice' => $goods['goods_storePrice'],
                'goods_purchasePrice' => $goods['goods_purchasePrice'],
                'goods_pointsPrice' => $goods['goods_pointsPrice'],
                'goods_marketPrice' => $goods['goods_marketPrice'],
                'goods_points' => $goods['goods_points'],
                'goods_from' => $goods['goods_from'],
                'goods_groupID' => $goods['goods_groupID'],
                'virtual_id' => $goods['virtual_id'],
                'recordPrice' => isset($goods['recordPrice']) ? $goods['recordPrice'] : 0,
                'goods_status' => isset($goods['goods_status']) ? $goods['goods_status'] : 2
            ];

        }

        /**
         * ======================
         * 订单支付
         * ======================
         */
        $bill_pay_data = [];
        foreach($pay_data as $pay) {

            $bill_pay_data[] = [
                'uuid' => $goods['uuid'],
                'timeStamp' => $pay['timeStamp'],
                'creator' => $pay['creator'],
                'createTime' => $pay['createTime'],
                'bill_no' => $pay['bill_no'],
                'payTypeID' => $pay['payTypeID'],
                'payTypeName' => $pay['payTypeName'],
                'type' => $pay['type'],
                'pay_amount' => $pay['pay_amount'],
                'deduct_amount' => $pay['deduct_amount'],
                'pay_time' => $pay['pay_time']
            ];
        }

        //订单使用优惠券
        $use_coupon_obj = null;
        if (isset($bill_array['use_coupon']) && !empty($bill_array['use_coupon'])) {
            $coupon = $bill_array['use_coupon'];
            $use_coupon_obj = new BillUseCardCoupon();
            $use_coupon_obj->uuid = $coupon['uuid'];
            $use_coupon_obj->timeStamp = $coupon['timeStamp'];
            $use_coupon_obj->createTime = $coupon['createTime'];
            $use_coupon_obj->creator = $coupon['creator'];
            $use_coupon_obj->bill_no = $bill_no;
            $use_coupon_obj->card_id = $coupon['couponID'];
            $use_coupon_obj->card_name = $coupon['couponName'];
            $use_coupon_obj->card_type = $coupon['cardType'];
            $use_coupon_obj->barcode = $coupon['code'];
            $use_coupon_obj->amount = $coupon['amount'];
            $use_coupon_obj->code_limit_amount = $coupon['code_limit_amount'];
        }

        try {

            DB::beginTransaction();

            //保存订单主表
            $bill_master_obj->save();

            //使用优惠券
            if (!empty($use_coupon)) {

                $coupon_master = CardCoupon::find($use_coupon['couponID']);
                if (!$coupon_master) {
                    throw new Exception('优惠券信息未找到', 404);
                }

                //获取已使用的redis数据
                $redis_used_num = Redis::get('EBSIG_CARD_COUPON_USED_' . $use_coupon['couponID']);
                if (empty($redis_used_num)){
                    Redis::set('EBSIG_CARD_COUPON_USED_' . $use_coupon['couponID'], $coupon_master->useNum);
                }

                Redis::incr('EBSIG_CARD_COUPON_USED_' . $use_coupon['couponID']);

                $redis_used_num = Redis::get('EBSIG_CARD_COUPON_USED_' . $use_coupon['couponID']);

                if ($redis_used_num > $coupon_master->total_num){
                    Redis::set('EBSIG_CARD_COUPON_USED_' . $use_coupon['couponID'], $coupon_master->total_num);
                    throw new Exception('优惠券已用完', 404);
                }

                if ($coupon_master->provide_type == 3) {
                    $coupon_code_array = AlipayCustomerCardMap::where([
                        'pcustID' => $bill_array['pcustID'],
                        'barcode' => $use_coupon['code'],
                        'code_status' => 1
                    ])->first();

                    if (!$coupon_code_array) {
                        throw new Exception('优惠券已被使用', 404);
                    }

                    $affected_rows = AlipayCustomerCardMap::where([
                        'uuid' => $coupon_code_array->uuid,
                        'pcustID' => $bill_array['pcustID'],
                        'barcode' => $use_coupon['code'],
                        'code_status' => 1
                    ])->update([
                        'bill_no' => $bill_no,
                        'code_status' => 2,
                        'used_time' => Carbon::now()
                    ]);

                } else {
                    $affected_rows = AlipayCustomerCardMap::where([
                        'pcustID' => $bill_array['pcustID'],
                        'barcode' => $use_coupon['code'],
                        'code_status' => 1
                    ])->update([
                        'bill_no' => $bill_no,
                        'code_status' => 2,
                        'used_time' => Carbon::now()
                    ]);
                }
                if ($affected_rows <= 0) {
                    throw new Exception('优惠券已被使用', 404);
                }
            }

            //保存订单商品
            DB::table('bill_goods')->insert($bill_goods_data);

            //保存订单支付
            DB::table('bill_pay')->insert($bill_pay_data);

            //保存订单使用优惠券
            if (!is_null($use_coupon_obj)) {
                $use_coupon_obj->save();
            }

            DB::commit();

        } catch (Exception $e) {

            DB::rollback();

            if ($e->getCode() > 0) {
                return [ 'code' => 400, 'message' => $e->getMessage()];
            } else {
                return [ 'code' => 500, 'message' => '订单保存失败'];
            }
        }

        return [ 'code' => 200, 'message' => 'ok'];

    }

    /**
     * 获取购物车信息
     * @param $auto_code
     * @return array
     */
    public static function getCartInfo($auto_code)
    {

        $bill_array = Redis::get($auto_code);

        if (!$bill_array) {
            $bill_array = self::createCartStructure();
        } else {
            $bill_array = json_decode($bill_array, true);
        }

        return $bill_array;
    }

    /**
     * 统计订单商品数据
     * @param array $goods_data 商品数组
     */
    private function totalBillGoodsData($goods_data, $amount_flg=1)
    {

        $this->totalMoney += $goods_data['salePrice'] * $goods_data['goods_amount'];           //商品总金额
        $this->totalPaid += $goods_data['price'] * $goods_data['goods_amount'];                 //商品实售总金额
        $this->totalPoints += $goods_data['salePoints'] * $goods_data['goods_amount'];         //商品总赠送积分
        $this->pointsPrice += $goods_data['addPoints'] * $goods_data['goods_amount'];          //商品总积分价格
        if ($amount_flg == 1) {
            $this->totalAmount += $goods_data['goods_amount']; //商品总数量
        }
    }

    /**
     * 创建订单商品数据
     * @param array $goods_data 商品数组
     * @param int $goods_from 商品来源
     * @param int $goods_groupID 商品活动id
     */
    private function createBillGoodsData($goods_data, $goods_from, $goods_groupID = 0)
    {

        $goodsID = isset($goods_data['goodsID']) ? $goods_data['goodsID'] : 0;

        $postID = isset($goods_data['postID']) ? $goods_data['postID'] : 0;

        if (!isset($goods_data['bill_goods_no']) || empty($goods_data['bill_goods_no'])) {
            $goods_data['bill_goods_no'] = generate_seqno('seqno_bill_goods');
        }

        $this->billGoodsData['list'][] = array(
            'uuid' => str_replace('-', '', Uuid::uuid()),
            'timeStamp' => $this->datetime,
            'creator' => $this->operator,
            'createTime' => $this->datetime,
            'bill_no' => $this->bill_no,
            'bill_goods_no' => $goods_data['bill_goods_no'],
            'goods_goodsID' => $goodsID,
            'goods_postID' => $postID,
            'goods_name' => $goods_data['goodsName'],
            'goods_spec' => isset($goods_data['spec']) ? $goods_data['spec'] : '默认',
            'goods_amount' => $goods_data['goods_amount'],
            'goods_marketPrice' => $goods_data['marketPrice'],
            'goods_storePrice' => $goods_data['salePrice'],
            'goods_purchasePrice' => $goods_data['price'],
            'goods_pointsPrice' => $goods_data['addPoints'],
            'goods_points' => $goods_data['salePoints'],
            'goods_from' => $goods_from,
            'goods_groupID' => $goods_groupID,
            'virtual_id' => 0,
            'goods_status' => 2,
            'product_code' => isset($goods_data['product_code']) ? $goods_data['product_code'] : 0
        );

        //用于检查库存的商品数据
        if ($goodsID != 0) {
            if (isset($this->billGoodsData['store'][$goodsID])) {
                $this->billGoodsData['store'][$goodsID]['goods_amount'] += $goods_data['goods_amount'];
            } else {
                $this->billGoodsData['store'][$goodsID] = array(
                    'goodsID' => $goodsID,
                    'goodsName' => $goods_data['goodsName'],
                    'goods_amount' => $goods_data['goods_amount'],
                    'product_code' => $goods_data['product_code'],
                    'product_spec' => $goods_data['product_spec'],
                    'goodsType' => isset($goods_data['goodsType'])?$goods_data['goodsType']:1
                );
            }

            //记录商品名称
            $this->billGoodsData['name'][] = $goods_data['goodsName'];
        }
    }

    /**
     * 订单订单应付款
     * @param double $deliver_fee 运费
     */
    private function calculationBillPayable( $deliver_fee )
    {

        //订单总金额
        $payable = $this->totalPaid - $this->couponMoney;
        if ($payable <= 0) {
            $payable = 0;
        }

        $payable += $deliver_fee;

        if ($payable < 0) {
            $payable = 0;
        }

        $this->payable = round($payable, 2);

    }

    /**
     * 创建订单支付数据
     * @param int $payTypeID 支付方式id
     * @param string $payTypeName 支付方式名称
     * @param int $type 支付方式类型
     * @param double $pay_amount 支付金额
     * @param double $deduct_amount 已支付金额
     */
    public function createBillPayData($payTypeID, $payTypeName, $type, $pay_amount, $deduct_amount = 0.00)
    {

        $this->billPayData['list'][] = array(
            'uuid' => str_replace('-', '', Uuid::uuid()),
            'timeStamp' => $this->datetime,
            'creator' => $this->operator,
            'createTime' => $this->datetime,
            'bill_no' => $this->bill_no,
            'payTypeID' => $payTypeID,
            'payTypeName' => $payTypeName,
            'type' => $type,
            'pay_amount' => $pay_amount,
            'deduct_amount' => $deduct_amount,
            'pay_time' => $pay_amount == 0 ? $this->datetime : null
        );

        $this->billPayData['id'][] = $payTypeID;

        $this->billPayData['name'][] = $payTypeName;
    }

    /**
     * 初始化购物车数据结构
     * @return array
     */
    public static function createCartStructure()
    {

        $bill_array = [

            'bill_no' => null,

            'bill_status' => 0,

            //订单主表
            'master' => [
                'bill_totalMoney' => 0,
                'bill_totalPaid' => 0,
                'bill_totalPoints' => 0,
                'bill_pointsPrice' => 0,
                'bill_subtract_money' => 0,
                'bill_coupon_money' => 0,
                'bill_payable' => 0,
                'bill_total_amount' => 0,
                'billType' => 1,
                'remark' => null,
                'payment_method_id' => null
            ],

            //订单配置
            'bill_config_id' => 1,

            'change_time' => null,

            'message' => null,

            //订单商品
            'goods' => [
                'general' => [],
                'shopping_bag' => []
            ],

            //赠送优惠券
            'gift_coupon' => [],

            //订单促销
            'bill_promotion' => []
        ];

        return $bill_array;

    }
}